Page({
    /**
     * 页面的初始数据
     */
    data: {
        time: '00:00:00',

        player_msg: '停止',
        recoder_msg: '录音',

        play_state: 0, //0 表示停止录音，1 表示播放录音，2 表示暂停
        is_recode: false,
        has_voice: false,

        recoder_icon: "iconfont icon-luyin icon",
        player_icon: "iconfont icon-tingzhi icon",
        voiceBase: null
    },
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function () {
        this.recorderManager = wx.getRecorderManager()
        this.innerAudioContext = wx.createInnerAudioContext()
        this.tempFilePath;
        this.TimeAdd();
    },

    PrefixZero: function(num, n) {
        return (Array(n).join(0) + num).slice(-n);
    },

    TimeValueHandle: function() {
        var that = this;
        var time = this.data.time;
        var list = time.split(":");
        var h = Number(list[0]);
        var m = Number(list[1]);
        var s = Number(list[2]);
        
        s++;
        if(s==60){
            s=0;
            m++;
        }

        if(m==60){
            m=0;
            h++;
        }

        var res=that.PrefixZero(h,2)+":"+that.PrefixZero(m,2)+":"+that.PrefixZero(s,2);
        that.setData({
            time:res
        })
    },

    TimeAdd(){
        var that = this;
        if(that.data.is_recode === true){
            setTimeout(function(){
                // console.log("qajshit");
                that.TimeValueHandle();
                that.TimeAdd();
            },1000);
        }else{
            setTimeout(function(){
                that.TimeAdd();
            },100);
        }
    },

    //开始录音
    start_pause: function () {
        var that = this;
        //开始录音
        if (this.data.play_state == 0) {
            if (!this.data.is_recode) {

                const options = {
                    sampleRate: 48000, //采样率
                    numberOfChannels: 1, //录音通道数
                    encodeBitRate: 96000, //编码码率
                    format: 'mp3' //音频格式
                }
                this.recorderManager.start(options);
                this.recorderManager.onStart(() => {
                    console.log("开始录音");
                })
                this.setData({
                    recoder_msg: "暂停",
                    is_recode: true,
                    has_voice: true,
                    recoder_icon: "iconfont icon-zanting icon"
                })
                //错误回调
                this.recorderManager.onError((res) => {
                    console.log(res);
                })
            } else {
                //暂停录音
                
                this.recorderManager.onPause()
                console.log("暂停录音");
                this.setData({
                    recoder_msg: "继续",
                    is_recode: false,
                    has_voice: true,
                    recoder_icon: "iconfont icon-luyin icon"
                });
            }
        } else {
            wx.showToast({
                title: '请先停止录音',
                icon: 'error',
                duration: 2000
            })
        }
    },
    play() {
        //停止，播放与暂停声音
        this.innerAudioContext.autoplay = true
        this.innerAudioContext.src = this.tempFilePath
        if (this.data.has_voice) {
            //停止录音
            if (this.data.play_state == 0) {
                this.recorderManager.stop();
                this.recorderManager.onStop((res) => {
                    this.tempFilePath = res.tempFilePath;
                    console.log('停止录音', res.tempFilePath)
                    wx.getFileSystemManager().readFile({
                        filePath: res.tempFilePath, //选择图片返回的相对路径
                        encoding: "base64", //这个是很重要的
                        success: r => { //成功的回调
                            //返回base64格式
                            // console.log('data:image/png;base64,' + r.data)

                            this.setData({
                                voiceBase: r.data
                            })

                        }
                    })
                    this.setData({
                        recoder_msg: "重录",
                        player_msg: "播放",
                        play_state: 1,
                        is_recode: false,
                        has_voice: true,
                        recoder_icon: "iconfont icon-luyin icon",
                        player_icon: "iconfont icon-kaishi icon"
                    })
                })
            }
            if (this.data.play_state == 1) {
                this.innerAudioContext.onPlay(() => {
                    console.log('开始播放')
                    this.setData({
                        player_msg: "暂停",
                        play_state: 2,
                        player_icon: "iconfont icon-zanting1 icon"
                    })
                }) || this.innerAudioContext.play(() => {
                    console.log('开始播放')
                    this.setData({
                        player_msg: "暂停",
                        play_state: true,
                        player_icon: "iconfont icon-zanting1 icon"
                    })
                });
                this.innerAudioContext.onEnded(() => {
                    console.log('重新播放');
                    this.setData({
                        player_msg: "重播",
                        play_state: false,
                        player_icon: "iconfont icon-zhongbo icon"
                    })
                })
                this.innerAudioContext.onError((res) => {
                    console.log(res.errMsg)
                    console.log(res.errCode)
                })
            }
            //暂停录音
            if (this.data.play_state == 2) {
                this.innerAudioContext.pause();
                console.log('暂停播放');
                this.setData({
                    player_msg: "继续",
                    play_state: 1,
                    player_icon: "iconfont icon-kaishi icon"
                })
            }
        } else {
            wx.showToast({
                title: '未录音',
                icon: 'error',
                duration: 2000
            })
        }

    },
    //上传录音
    upload: function () {
        if (this.data.play_state == 0) {
            wx.showToast({
                title: '请先停止录音',
                icon: 'error',
                duration: 2000
            })
        } else {
            this.setData({
                play_state: 0,
                player_msg: "停止",
                player_icon: "iconfont icon-tingzhi icon"
            })
            var tempFilePath = this.tempFilePath;
            var that = this;
            wx.showActionSheet({
                itemList: ['确认'],
                success(choose) {
                    console.log(choose.tapIndex)
                    wx.request({
                        url: "http://175.27.243.30:8080/api/predict/uploadVoice", //演示域名、自行配置
                        method: 'post',
                        header: {
                            "Content-Type": "application/json"
                        },

                        data: {
                            openid: '1234',
                            baseVoice: that.data.voiceBase

                        },
                        success: function (res) {
                            console.log(res);
                            wx.showToast({
                                title: '上传成功',
                                icon: 'success',
                                duration: 2000
                            })
                        },
                        fail: function () {
                            wx.showToast({
                                title: '上传失败',
                                icon: 'warn',
                                duration: 2000
                            })
                        },
                        complete: function (res) {}
                    })
                },
                fail(choose) {
                    console.log(choose.errMsg)
                    wx.showToast({
                        title: '上传取消',
                        icon: 'fail',
                        duration: 2000
                    })
                }
            })
        }
    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {
        this.setData({
            time:"00:00:00"
        });

        if (typeof this.getTabBar === 'function' && this.getTabBar()) {
            this.getTabBar().setData({
                selected: 1
            })
        }

    }
})